<template>
   
    <el-container>
      <!-- 主体内容 -->
      <el-main>
        <!-- 操作栏 -->
        <div class="toolbar">
          <div class="left-actions">
            <el-button type="primary" @click="onAdd">
              <el-icon><Plus /></el-icon>新增
            </el-button>
            <el-button 
              type="danger" 
              @click="handleBatchDelete" 
              :disabled="selectedRows.length === 0"
              :loading="batchDeleteLoading"
            >
              <el-icon><Delete /></el-icon>
              批量删除
              <span v-if="selectedRows.length > 0" class="badge">{{ selectedRows.length }}</span>
            </el-button>
            <el-button type="info" @click="fetchData" :loading="loading">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
            <el-button type="warning" @click="manualVerifyDatabase" size="small">
              <el-icon><View /></el-icon>验证数据库
            </el-button>
          </div>
          <div class="search-box">
            <el-input v-model="searchKeyword" placeholder="搜索商品名称" clearable @clear="fetchData" style="width: 200px;">
              <template #append>
                <el-button @click="fetchData" :loading="loading">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>

        <div class="content-container">
          <!-- 表格 -->
          <el-table 
            :data="tableData" 
            border 
            v-loading="loading"
            element-loading-text="加载中..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.7)"
            :empty-text="loading ? '加载中...' : '暂无数据'"
            @selection-change="handleSelectionChange"
            row-key="id"
            :highlight-current-row="true"
          >
            <el-table-column type="selection" width="50" :selectable="rowSelectable"></el-table-column>
            <el-table-column prop="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="name" label="商品名称" min-width="120"></el-table-column>
            <el-table-column prop="batch" label="生产批次" min-width="140"></el-table-column>
            <el-table-column prop="days" label="保质期(天)" width="90"></el-table-column>
            <el-table-column prop="license" label="生产许可证号" min-width="140"></el-table-column>
            <el-table-column prop="company" label="生产企业" min-width="140"></el-table-column>
            <el-table-column prop="percent" label="信息完整度" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.percent === 100 ? 'success' : (scope.row.percent >= 80 ? 'warning' : 'danger')"
                  disable-transitions
                >
                  {{ scope.row.percent }}%
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdBy" label="创建人" width="100">
              <template #default="scope">
                <span>{{ scope.row.createdBy || '未知' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" width="160">
              <template #default="scope">
                <span>{{ scope.row.createdTime || '未知' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="modifiedBy" label="修改人" width="100">
              <template #default="scope">
                <span>{{ scope.row.modifiedBy || '未知' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="scope">
                <div class="table-actions">
                  <el-button type="primary" size="small" @click="onDetail(scope.row)">
                    <el-icon><View /></el-icon>详情
                  </el-button>
                  <el-button type="success" size="small" @click="onEdit(scope.row)">
                    <el-icon><Edit /></el-icon>修改
                  </el-button>
                  <el-button type="danger" size="small" @click="onDelete(scope.row)" :loading="scope.row.deleting">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </div>
                <div class="table-actions" style="margin-top: 5px;">
                  <el-button type="info" size="small" @click="onExport(scope.row)">
                    <el-icon><Download /></el-icon>导出溯源码
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <div v-if="total === 0">暂无数据，无需分页</div>
            <el-pagination
              v-else
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[3, 5, 10, 20, 50]"
              :disabled="loading"
              :hide-on-single-page="false"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
            <div class="pagination-debug">
              <span>当前页: {{ currentPage }}, 每页条数: {{ pageSize }}, 总条数: {{ total }}</span>
              <span v-if="loading" class="loading-text">加载中...</span>
            </div>
          </div>
        </div>

        <!-- 新增/修改商品弹窗 -->
        <el-dialog
          v-model="dialogVisible"
          :title="isEditMode ? '修改基本信息' : '新增基本信息'"
          width="480px"
          @close="handleDialogClose"
          @open="handleDialogOpen"
          :close-on-click-modal="false"
          :before-close="handleBeforeClose">
          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" label-position="top">
            <el-form-item label="商品名称" prop="productId" required>
              <el-select v-model="form.productId" placeholder="请选择商品名称">
                <el-option
                  v-for="item in productOptions"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生产批次" prop="productionBatch" required>
              <div class="batch-input-group">
                <el-input v-model="form.productionBatch" placeholder="自动生成的生产批次" />
                <el-button type="primary" icon="Refresh" @click="generateProductionBatch" title="刷新生产批次号"></el-button>
              </div>
            </el-form-item>
            <el-form-item label="保质期(天)" prop="shelfLife" required>
              <el-input v-model.number="form.shelfLife" placeholder="请输入保质期" type="number" />
            </el-form-item>
            <el-form-item label="生产许可证号" prop="productionLicenseNumber" required>
              <el-input v-model="form.productionLicenseNumber" placeholder="请输入生产许可证号" />
            </el-form-item>
            <el-form-item label="生产企业" prop="manufacturerName" required>
              <el-input v-model="form.manufacturerName" placeholder="请输入生产企业" />
            </el-form-item>
            <el-form-item label="封面图" prop="photoUrl" required>
              <el-upload
                class="avatar-uploader"
                action="/api/FileUpload/upload"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-progress="handleUploadProgress"
                :before-upload="beforeAvatarUpload"
                :headers="{}"
                :data="{ key: 'enterprise_photos' }"
                name="file"
              >
                <img v-if="form.photoUrl" :src="form.photoUrl" class="avatar" />
                <div v-else class="upload-placeholder">
                  <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传</div>
                </div>
              </el-upload>
              <div class="upload-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>支持 JPG、PNG 格式，文件大小不超过 5MB</span>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="confirmClose">取消</el-button>
            <el-button type="info" @click="debugFormData" size="small">调试</el-button>
            <el-button type="primary" @click="onSave">
              {{ isEditMode ? '更新' : '保存' }}
            </el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>

</template>

<script setup lang="ts">
import { ref, onMounted, markRaw, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Loading, Refresh, Delete, Search, View, Edit, Download, Check, InfoFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 产品下拉选项
interface ProductOption {
  productId: number
  productName: string
}
const productOptions = ref<ProductOption[]>([])

// 获取产品列表
const fetchProductOptions = async () => {

  try {
    const response = await axios.get('/api/Product/GetProductList')
  

    if (response.data && response.data.code === 300 && response.data.data) {
      productOptions.value = response.data.data
     
    } else {
      ElMessage.error('获取产品列表失败: ' + (response.data?.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('获取产品列表失败: ' + ((error as any)?.message || '网络错误'))
  }
}

const dialogVisible = ref(false)
const formRef = ref()
const uploadLoading = ref(false)
const isEditMode = ref(false) // 是否为编辑模式
const editingId = ref(0) // 正在编辑的记录ID

// 修改表单字段，与后端API保持一致
const form = ref({
  traceabilityId: 0, // 溯源信息ID，用于更新操作
  productId: 0,
  productionBatch: '',
  shelfLife: 0, // 保质期
  productionLicenseNumber: '', // 生产许可证号
  manufacturerName: '', // 生产企业
  informationCompleteness: 0, // 信息完整度
  photoUrl: '', // 存储上传后的图片URL
  createdBy: '黑泽',
  modifiedBy: '黑泽' // 修改人
})

// 监听对话框打开，加载下拉选项
const handleDialogOpen = () => {
  fetchProductOptions();
  // 只在新增模式下自动生成生产批次
  if (!isEditMode.value) {
    generateProductionBatch();
  }
};

// 生成生产批次号
const generateProductionBatch = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  // 格式: 年月日时分秒
  const batchNumber = `${year}${month}${day}${hours}${minutes}${seconds}`;
  console.log('自动生成生产批次:', batchNumber);
  form.value.productionBatch = batchNumber;
};

// 处理对话框关闭前的确认
const handleBeforeClose = (done: () => void) => {
  // 检查是否有未保存的更改
  if (form.value.productId || form.value.productionBatch) {
    ElMessageBox.confirm('确定关闭？未保存的数据将丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      resetForm(); // 重置表单
      done(); // 关闭对话框
    }).catch(() => {
      // 取消关闭
    });
  } else {
    resetForm();
    done();
  }
};

// 处理对话框关闭
const handleDialogClose = () => {
  console.log('对话框关闭');
  resetForm();
};

// 确认关闭对话框
const confirmClose = () => {
  if (form.value.productId || form.value.productionBatch) {
    ElMessageBox.confirm('确定关闭？未保存的数据将丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      dialogVisible.value = false;
    }).catch(() => {
      // 取消关闭
    });
  } else {
    dialogVisible.value = false;
  }
};

const rules = {
  productId: [{ required: true, message: '请选择商品名称', trigger: 'change' }],
  productionBatch: [{ required: true, message: '请输入生产批次', trigger: 'blur' }],
  shelfLife: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { type: 'number', message: '保质期必须为数字', trigger: 'blur' }
  ],
  productionLicenseNumber: [{ required: true, message: '请输入生产许可证号', trigger: 'blur' }],
  manufacturerName: [{ required: true, message: '请输入生产企业', trigger: 'blur' }],
  photoUrl: [{ required: true, message: '请上传封面图', trigger: 'change' }]
}

// 重置表单，确保清除所有内容
const resetForm = () => {
  console.log('重置表单');
  form.value = {
    traceabilityId: 0,
    productId: 0,
    productionBatch: '',
    shelfLife: 0,
    productionLicenseNumber: '',
    manufacturerName: '',
    informationCompleteness: 0,
    photoUrl: '',
    createdBy: '黑泽',
    modifiedBy: '黑泽'
  };

  // 重置编辑模式
  isEditMode.value = false;
  editingId.value = 0;

  // 延迟清除验证状态，避免验证错误闪现
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
};

// 添加产品前检查表单
const checkFormData = () => {
  console.log('=== 🔍 检查表单数据完整性 ===');
  console.log('📋 当前表单数据:', {
    productId: form.value.productId,
    productionBatch: form.value.productionBatch,
    shelfLife: form.value.shelfLife,
    productionLicenseNumber: form.value.productionLicenseNumber,
    manufacturerName: form.value.manufacturerName,
    photoUrl: form.value.photoUrl
  });

  // 检查商品名称
  if (!form.value.productId || form.value.productId === 0) {
    console.error('❌ 表单缺少必填字段: 商品名称');
    console.error('当前productId值:', form.value.productId);
    ElMessage.warning('请选择商品名称');
    return false;
  }
  console.log('✅ 商品名称验证通过:', form.value.productId);
  
  // 检查生产批次
  if (!form.value.productionBatch || form.value.productionBatch.trim() === '') {
    console.error('❌ 表单缺少必填字段: 生产批次');
    console.error('当前productionBatch值:', form.value.productionBatch);
    ElMessage.warning('请填写生产批次');
    return false;
  }
  console.log('✅ 生产批次验证通过:', form.value.productionBatch);

  // 检查保质期
  if (!form.value.shelfLife || form.value.shelfLife <= 0) {
    console.error('❌ 表单缺少必填字段: 保质期');
    console.error('当前shelfLife值:', form.value.shelfLife);
    ElMessage.warning('请填写保质期（必须大于0）');
    return false;
  }
  console.log('✅ 保质期验证通过:', form.value.shelfLife);

  // 检查生产许可证号
  if (!form.value.productionLicenseNumber || form.value.productionLicenseNumber.trim() === '') {
    console.error('❌ 表单缺少必填字段: 生产许可证号');
    console.error('当前productionLicenseNumber值:', form.value.productionLicenseNumber);
    ElMessage.warning('请填写生产许可证号');
    return false;
  }
  console.log('✅ 生产许可证号验证通过:', form.value.productionLicenseNumber);

  // 检查生产企业
  if (!form.value.manufacturerName || form.value.manufacturerName.trim() === '') {
    console.error('❌ 表单缺少必填字段: 生产企业');
    console.error('当前manufacturerName值:', form.value.manufacturerName);
    ElMessage.warning('请填写生产企业');
    return false;
  }
  console.log('✅ 生产企业验证通过:', form.value.manufacturerName);

  // 删除所有 photoUrl 检查

  console.log('🎉 所有必填字段验证通过！');
  return true;
};

// 调试表单数据
const debugFormData = () => {
  console.log('=== 🐛 调试表单数据 ===');
  console.log('📋 完整表单数据:', JSON.stringify(form.value, null, 2));
  console.log('📦 产品选项:', productOptions.value);
  console.log('🔍 表单验证状态:');

  // 手动检查每个字段
  const checks = {
    '商品ID': form.value.productId,
    '生产批次': form.value.productionBatch,
    '保质期': form.value.shelfLife,
    '生产许可证号': form.value.productionLicenseNumber,
    '生产企业': form.value.manufacturerName,
    '图片URL': form.value.photoUrl
  };

  Object.entries(checks).forEach(([key, value]) => {
    const status = value ? '✅' : '❌';
    console.log(`${status} ${key}:`, value);
  });

  // 运行验证检查
  const isValid = checkFormData();
  console.log('🎯 验证结果:', isValid ? '通过' : '失败');

  ElMessage.info('调试信息已输出到控制台，请按F12查看');
};

// 调试API响应格式
const debugApiResponse = (response: any, operation: string) => {
  console.log(`=== 🔍 调试${operation}API响应 ===`);
  console.log('完整响应:', response);
  console.log('响应状态码:', response?.data?.code);
  console.log('响应消息:', response?.data?.message);
  console.log('响应数据:', response?.data?.data);
  console.log('响应成功标识:', response?.data?.success);
  
  // 分析响应格式
  const analysis = {
    '有code字段': !!response?.data?.code,
    '有message字段': !!response?.data?.message,
    '有data字段': !!response?.data?.data,
    '有success字段': !!response?.data?.success,
    '消息包含"成功"': response?.data?.message?.includes('成功') || false,
    '数据为true': response?.data?.data === true,
    '状态码为100': response?.data?.code === 100,
    '状态码为600': response?.data?.code === 600,
    '状态码为500': response?.data?.code === 500
  };
  
  console.log('响应格式分析:', analysis);
  
  return analysis;
};



// 保存方法
const onSave = async () => {
  if (!formRef.value) {
    return;
  }
  
  try {
    // 手动触发表单验证，并等待结果
    const valid = await new Promise<boolean>((resolve) => {
      formRef.value.validate((isValid: boolean) => {
        resolve(isValid);
      });
    });
    
    if (!valid) {
      ElMessage.warning('请填写所有必填字段');
      return;
    }
    
    // 检查表单数据完整性
    if (!checkFormData()) {
      return;
    }
    
    // 确保数值字段是数值类型
    const submitForm = {
      productId: Number(form.value.productId) || 0,
      productionBatch: form.value.productionBatch || '',
      shelfLife: Number(form.value.shelfLife) || 0,
      productionLicenseNumber: form.value.productionLicenseNumber || '',
      manufacturerName: form.value.manufacturerName || '',
      informationCompleteness: 100, // 设置默认值
      photoUrl: form.value.photoUrl || '',
      createdBy: form.value.createdBy || 'admin'
    };

    // 验证图片URL数据
    console.log('=== 图片URL数据验证 ===');
    // 删除图片URL验证

    if (!submitForm.photoUrl) {
      console.warn('警告：即将提交的数据中photoUrl为空！');
      ElMessage.warning('图片URL为空，请确保图片已正确上传');
    } else {
      console.log('✓ 图片URL验证通过，来自上传API响应，准备提交到数据库');
      console.log('✓ photoUrl 字段将保存图片的URL地址');
    }
    
    // 提交数据 - 根据模式选择API
    try {
      let response;
      if (isEditMode.value) {
        // 更新模式 - 根据Swagger API格式
        const updateForm = {
          traceabilityId: form.value.traceabilityId,
          productId: Number(form.value.productId) || 0,
          productionBatch: form.value.productionBatch || '',
          shelfLife: Number(form.value.shelfLife) || 0,
          productionLicenseNumber: form.value.productionLicenseNumber || '',
          manufacturerName: form.value.manufacturerName || '',
          informationCompleteness: Number(form.value.informationCompleteness) || 100,
          photoUrl: form.value.photoUrl || '',
          modifiedBy: form.value.modifiedBy || '黑泽'
        };

        console.log('更新数据:', updateForm);
        response = await axios.put('/api/TraceabilityInfo/Update', updateForm, {
          headers: { 'Content-Type': 'application/json' }
        });
      } else {
        // 新增模式
        response = await axios.post('/api/TraceabilityInfo/Add', submitForm, {
          headers: { 'Content-Type': 'application/json' }
        });
      }

      console.log('检查保存成功状态码，实际状态码:', response.data?.code);
      console.log('API响应:', response.data);
      
      // 调试API响应格式
      debugApiResponse(response, isEditMode.value ? '修改' : '新增');
      
      // 检查成功状态：支持多种成功状态码和成功消息
      const isSuccess = (
        response.data && (
          response.data.code === 100 || // 标准成功状态码
          response.data.code === 600 || // 更新成功状态码
          response.data.success === true || // 布尔成功标识
          (response.data.data === true && response.data.message?.includes('成功')) || // 数据为true且消息包含"成功"
          response.data.message?.includes('成功') // 消息包含"成功"
        )
      );
      
      if (isSuccess) {
        console.log('=== 数据库保存成功 ===');
        console.log('成功状态码:', response.data.code);
        console.log('成功消息:', response.data.message);

        // 验证保存的数据
        if (response.data.data) {
          console.log('保存到数据库的数据:', response.data.data);
        }

        ElMessage.success(isEditMode.value ? '修改成功' : '添加成功');
        dialogVisible.value = false;
        resetForm();

        // 刷新列表并验证数据
        await fetchData();

      } else {
        console.error('数据库保存失败:', response.data);
        const errorMessage = response.data?.message || response.data?.msg || '未知错误';
        ElMessage.error(`${isEditMode.value ? '修改' : '添加'}失败: ${errorMessage}`);
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error(`${isEditMode.value ? '修改' : '添加'}失败，请重试`);
    }
  } catch (validationError) {
    ElMessage.warning('请填写必填字段');
  }
};

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const batchDeleteLoading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5); // 默认每页显示3条数据
const searchKeyword = ref(''); // 搜索关键词
const selectedRows = ref<any[]>([]); // 选中的行数据

// 获取表格数据
const fetchData = async () => {
  console.log('开始获取数据，当前页码:', currentPage.value, '每页条数:', pageSize.value);
  loading.value = true;
  
  // 清空表格数据，显示加载状态
  tableData.value = [];
  
  try {
    const params: any = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
    };
    if (searchKeyword.value) {
      params.productName = searchKeyword.value;
    }

    console.log('请求参数:', params);
    console.log('请求URL:', '/api/TraceabilityInfo/GetAll');
    
    const response = await axios.get('/api/TraceabilityInfo/GetAll', {
      params: params
    });
    
    console.log('API响应状态:', response.status);
    console.log('API响应数据:', response.data);
    
    if (response.data && response.data.code === 300) {
      // API返回结构: { code, message, data: { totalCount, pageIndex, pageSize, totalPages, items[] } }
      const responseData = response.data.data || {};
      const items = responseData.items || [];

      console.log('=== API数据结构分析 ===');
      console.log('responseData:', responseData);
      console.log('items数组:', items);
      console.log('items数组长度:', items.length);
      if (items.length > 0) {
        console.log('第一个item的结构:', items[0]);
        console.log('第一个item的所有字段:', Object.keys(items[0]));
      }

      // 更新分页信息
      total.value = responseData.totalCount || 0;
      
      // 确保当前页码与API返回一致
      if (responseData.pageIndex && responseData.pageIndex !== currentPage.value) {
        console.log('更新当前页码:', responseData.pageIndex);
        currentPage.value = responseData.pageIndex;
      }
      
      console.log('分页信息:', {
        totalCount: responseData.totalCount,
        pageIndex: responseData.pageIndex,
        pageSize: responseData.pageSize,
        totalPages: responseData.totalPages
      });
      
      console.log('获取到的数据项数量:', items.length);
      
      // 转换数据格式，匹配表格列
      tableData.value = items.map((item: any, index: number) => {
        console.log('映射单个数据项:', item);
        return {
          index: (currentPage.value - 1) * pageSize.value + index + 1,
          name: item.productName || item.name || '',
          batch: item.productionBatch || item.batch || '',
          days: item.shelfLife || item.days || 0,
          license: item.productionLicenseNumber || item.license || '',
          company: item.manufacturerName || item.company || '',
          percent: item.informationCompleteness || item.percent || 0,
          id: item.traceabilityId || item.id || 0,
          photoUrl: item.photoUrl || '',
          createdBy: item.createdBy || item.createUser || '未知',
          createdTime: item.createdTime || item.createTime || '',
          modifiedBy: item.modifiedBy || item.updateUser || '未知',
          raw: item,
          deleting: false
        };
      });
      
      // 如果当前页没有数据但总数不为0，尝试获取前一页
      if (tableData.value.length === 0 && total.value > 0 && currentPage.value > 1) {
        console.log('当前页没有数据，尝试获取前一页');
        currentPage.value--;
        await fetchData();
        return;
      }
      
      console.log('转换后的表格数据:', tableData.value);
    } else {
      tableData.value = [];
      total.value = 0;
      console.error('API返回错误:', response.data);
      ElMessage.error(`获取数据失败: ${response.data?.msg || response.data?.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    tableData.value = [];
    total.value = 0;
    ElMessage.error('获取数据失败，请检查网络连接');
  } finally {
    loading.value = false;
    console.log('数据获取完成');
  }
};

// 页码变化
const handleCurrentChange = (val: number) => {
  console.log('页码变化:', val);
  currentPage.value = val;
  fetchData();
};

// 每页条数变化
const handleSizeChange = (val: number) => {
  console.log('每页条数变化:', val);
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  fetchData();
};

// 新增操作
const onAdd = () => {
  // 重置表单并设置为新增模式
  resetForm();
  isEditMode.value = false;
  editingId.value = 0;

  // 打开对话框
  dialogVisible.value = true;
};

const onDetail = (row: any) => {
  // 跳转到详情页面，传递生产批次数据
  router.push({
    name: 'ProductDetail',
    params: {
      id: row.id
    },
    query: {
      batch: row.batch,
      // 删除 photoUrl 数据
    }
  });
};
// 编辑操作
const onEdit = (row: any) => {
  console.log('编辑行数据:', row);

  // 设置编辑模式
  isEditMode.value = true;
  editingId.value = row.id;

  // 填充表单数据
  form.value = {
    traceabilityId: row.id,
    productId: row.raw?.productId || 0,
    productionBatch: row.batch || '',
    shelfLife: row.days || 0,
    productionLicenseNumber: row.license || '',
    manufacturerName: row.company || '',
    informationCompleteness: row.percent || 0,
    photoUrl: row.photoUrl || '',
    createdBy: row.raw?.createdBy || '黑泽',
    modifiedBy: '黑泽'
  };

  // 打开对话框
  dialogVisible.value = true;
}
const onExport = async (row: any) => {
  try {
    console.log('开始导出溯源码，ID:', row.id);
    
    // 显示加载状态
    ElMessage.info('正在生成导出文件...');
    
    const response = await axios.get(`/api/ImageUpload/ExportTraceabilityInfo/${row.id}`, {
      responseType: 'blob', // 重要：设置响应类型为blob
      headers: {
        'Accept': '*/*'
      }
    });
    
    console.log('导出响应:', response);
    
    // 从响应头获取文件名
    const contentDisposition = response.headers['content-disposition'];
    let filename = `TraceabilityInfo_${row.name}_${new Date().toISOString().slice(0, 10)}.csv`;
    
    if (contentDisposition) {
      // 尝试从content-disposition头中提取文件名
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '');
      }
    }
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success(`导出成功: ${filename}`);
    
  } catch (error: any) {
    console.error('导出失败:', error);
    
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
      
      if (error.response.status === 404) {
        ElMessage.error('未找到该记录，无法导出');
      } else if (error.response.status === 500) {
        ElMessage.error('服务器错误，导出失败');
      } else {
        ElMessage.error(`导出失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络');
    } else {
      ElMessage.error('导出失败，请重试');
    }
  }
};
// 删除操作
const onDelete = async (row: any) => {
  try {
    // 设置行的状态，防止重复点击
    if (row.deleting) {
      return;
    }
    
    await ElMessageBox.confirm(
      `确定要删除 "${row.name}" 吗？删除后无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(Delete),
        confirmButtonClass: 'el-button--danger',
        distinguishCancelAndClose: true
      }
    );
    
    // 设置当前行的删除状态
    row.deleting = true;
    
    try {
      // 调用删除API
      const response = await axios.delete(`/api/TraceabilityInfo/Delete/${row.id}`, {
        params: {
          deleteBy: '黑泽' // 删除人
        }
      });
      
      console.log('删除响应:', response.data);
      console.log('检查删除成功状态码，实际状态码:', response.data?.code);
      
      // 调试API响应格式
      debugApiResponse(response, '删除');

      // 检查删除成功状态：支持多种成功状态码和成功消息
      const isDeleteSuccess = (
        response.data && (
          response.data.code === 500 || // 删除成功状态码
          response.data.code === 100 || // 标准成功状态码
          response.data.success === true || // 布尔成功标识
          response.data.message?.includes('成功') // 消息包含"成功"
        )
      );

      if (isDeleteSuccess) {
        ElMessage({
          type: 'success',
          message: '删除成功！',
          duration: 2000
        });
        
        // 直接刷新数据，不再使用本地过滤
        fetchData();
      } else {
        const errorMessage = response.data?.message || response.data?.msg || '未知错误';
        ElMessage({
          type: 'error',
          message: `删除失败: ${errorMessage}`,
          duration: 3000
        });
        
        // 删除失败时也刷新数据，确保显示最新状态
        fetchData();
      }
    } catch (error) {
      console.error('删除出错:', error);
      ElMessage({
        type: 'error',
        message: '删除失败，请检查网络连接',
        duration: 3000
      });
      
      // 发生错误时也刷新数据
      fetchData();
    } finally {
      // 恢复行状态
      row.deleting = false;
    }
  } catch {
    // 用户取消删除
    ElMessage({
      type: 'info',
      message: '已取消删除',
      duration: 1000
    });
  }
};

// 批量删除操作
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的商品');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个商品吗？删除后无法恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(Delete),
        confirmButtonClass: 'el-button--danger',
        distinguishCancelAndClose: true
      }
    );
    
    batchDeleteLoading.value = true;

    console.log('=== 开始批量删除 ===');
    console.log('选中的行数据:', selectedRows.value);
    
    try {
      // 获取选中行的ID
      const traceabilityIds = selectedRows.value.map(row => row.id);

      console.log('批量删除ID列表:', traceabilityIds);

      // 尝试多种可能的API端点
      let response;
      let success = false;

      // 方法1：尝试POST方式的批量删除
      try {
        const requestBody = {
          traceabilityIds: traceabilityIds,
          deleteBy: '黑泽'
        };
        console.log('尝试POST批量删除，请求参数:', requestBody);
        response = await axios.post('/api/TraceabilityInfo/BatchDelete', requestBody, {
          headers: { 'Content-Type': 'application/json' }
        });
        success = true;
        console.log('POST批量删除成功:', response.data);
      } catch (postError) {
        console.log('POST批量删除失败，尝试其他方法:', postError);

        // 方法2：尝试DELETE方式的批量删除
        try {
          response = await axios.delete('/api/TraceabilityInfo/BatchDelete', {
            data: {
              traceabilityIds: traceabilityIds,
              deleteBy: '黑泽'
            },
            headers: { 'Content-Type': 'application/json' }
          });
          success = true;
          console.log('DELETE批量删除成功:', response.data);
        } catch (deleteError) {
          console.log('DELETE批量删除失败，使用逐个删除:', deleteError);

          // 方法3：逐个删除（作为备选方案）
          let successCount = 0;
          let failCount = 0;

          for (const id of traceabilityIds) {
            try {
              const singleResponse = await axios.delete(`/api/TraceabilityInfo/Delete/${id}`, {
                params: { deleteBy: '黑泽' }
              });
              // 检查单个删除成功状态
              const isSingleDeleteSuccess = (
                singleResponse.data && (
                  singleResponse.data.code === 500 || // 删除成功状态码
                  singleResponse.data.code === 100 || // 标准成功状态码
                  singleResponse.data.success === true || // 布尔成功标识
                  singleResponse.data.message?.includes('成功') // 消息包含"成功"
                )
              );
              
              if (isSingleDeleteSuccess) {
                successCount++;
              } else {
                failCount++;
              }
            } catch (singleError) {
              console.error(`删除ID ${id} 失败:`, singleError);
              failCount++;
            }
          }

          // 构造响应格式
          response = {
            data: {
              code: successCount > 0 ? 500 : 400,
              message: `成功删除 ${successCount} 个，失败 ${failCount} 个`,
              data: { successCount, failCount }
            }
          };
          success = true;
        }
      }

      if (success && response) {
        console.log('批量删除响应:', response.data);
        console.log('检查批量删除成功状态码，实际状态码:', response.data?.code);

        // 检查批量删除成功状态：支持多种成功状态码和成功消息
        const isBatchDeleteSuccess = (
          response.data && (
            response.data.code === 500 || // 删除成功状态码
            response.data.code === 100 || // 标准成功状态码
            response.data.success === true || // 布尔成功标识
            response.data.message?.includes('成功') // 消息包含"成功"
          )
        );

        if (isBatchDeleteSuccess) {
          const successCount = response.data.data?.successCount || selectedRows.value.length;
          const failCount = response.data.data?.failCount || 0;

          if (failCount > 0) {
            ElMessage({
              type: 'warning',
              message: `批量删除完成：成功 ${successCount} 个，失败 ${failCount} 个`,
              duration: 3000
            });
          } else {
            ElMessage({
              type: 'success',
              message: `成功删除 ${successCount} 个商品`,
              duration: 2000
            });
          }

          // 清空选中
          selectedRows.value = [];

          // 直接刷新数据
          fetchData();
        } else {
          ElMessage({
            type: 'error',
            message: `批量删除失败: ${response.data?.msg || response.data?.message || '未知错误'}`,
            duration: 3000
          });

          // 删除失败时也刷新数据
          fetchData();
        }
      } else {
        ElMessage({
          type: 'error',
          message: '批量删除失败：所有删除方法都不可用',
          duration: 3000
        });
        fetchData();
      }
    } catch (error) {
      console.error('批量删除出错:', error);
      ElMessage({
        type: 'error',
        message: '批量删除失败，请检查网络连接',
        duration: 3000
      });
      
      // 发生错误时也刷新数据
      fetchData();
    } finally {
      batchDeleteLoading.value = false;
    }
  } catch {
    // 用户取消批量删除
    ElMessage({
      type: 'info',
      message: '已取消批量删除',
      duration: 1000
    });
  }
};

// 处理表格行选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 判断行是否可选
const rowSelectable = (row: any) => {
  return !row.deleting;
};



// 初始化组件
const initComponent = async () => {
  console.log('初始化组件...');
  try {
    // 获取产品列表
    await fetchProductOptions();
    // 获取表格数据
    await fetchData();
    console.log('初始化完成');
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('初始化数据失败，请刷新页面重试');
  }
};

// 验证图片URL是否正确保存到数据库并显示在列表中
const verifyImageDataInList = (expectedPhotoUrl: string) => {
  console.log('=== 验证图片URL是否在列表中 ===');
  console.log('期望的图片URL:', expectedPhotoUrl);

  if (!expectedPhotoUrl) {
    console.warn('期望的图片URL为空，跳过验证');
    return;
  }

  // 在表格数据中查找包含该图片URL的记录
  const foundItems = tableData.value.filter(item => item.photoUrl === expectedPhotoUrl);

  if (foundItems.length > 0) {
    console.log('✓ 验证成功：图片URL已正确保存到数据库并显示在列表中');
    console.log('找到的记录数量:', foundItems.length);
    ElMessage.success('图片URL验证通过：已正确保存到数据库');
  } else {
    console.warn('⚠️ 验证失败：在列表中未找到包含该图片URL的记录');
    console.log('当前列表数据中的photoUrl:', tableData.value.map(item => ({
      id: item.id,
      name: item.name,
      photoUrl: item.photoUrl || '空'
    })));
    ElMessage.warning('图片URL验证失败：可能未正确保存到数据库');
  }
};

// 手动验证数据库中的图片base64数据（调试用）
const manualVerifyDatabase = async () => {
  console.log('=== 手动验证数据库数据 ===');
  try {
    const response = await axios.get('/api/TraceabilityInfo/GetAll', {
      params: {
        pageIndex: 1,
        pageSize: 100 // 获取更多数据进行验证
      }
    });

    if (response.data && response.data.code === 300) {
      const items = response.data.data?.items || response.data.data || [];
      console.log('数据库中的所有记录数量:', items.length);

      const itemsWithImages = items.filter((item: any) => item.photoUrl);
      console.log('包含图片base64数据的记录数量:', itemsWithImages.length);
      console.log('包含图片数据的记录:', itemsWithImages.map((item: any) => ({
        id: item.traceabilityId,
        name: item.productName,
        photoUrlLength: item.photoUrl?.length || 0,
        photoUrlPreview: item.photoUrl?.substring(0, 50) + '...' // 只显示前50个字符
      })));

      if (itemsWithImages.length === 0) {
        console.warn('⚠️ 数据库中没有找到包含图片base64数据的记录');
      } else {
        ElMessage.success(`数据库验证完成：找到 ${itemsWithImages.length} 条包含图片数据的记录`);
      }
    }
  } catch (error) {
    console.error('验证数据库数据时出错:', error);
  }
};

// 在组件挂载时执行初始化
onMounted(() => {
  console.log('组件已挂载');
  initComponent();

  // 添加全局调试函数，方便在浏览器控制台中调用
  (window as any).manualVerifyDatabase = manualVerifyDatabase;
  console.log('💡 调试提示：可在控制台中调用 manualVerifyDatabase() 来手动验证数据库数据');
});

const handleUploadSuccess = (response: any) => {
  console.log('图片上传响应:', response);
  
  if (response && response.success === true && response.url) {
    // 根据API响应格式，直接使用返回的url字段
    form.value.photoUrl = response.url;
    console.log('图片上传成功，URL已保存:', response.url);
    ElMessage.success('图片上传成功');
  } else {
    console.error('图片上传失败，响应格式不正确:', response);
    ElMessage.error('图片上传失败: ' + (response?.message || '未知错误'));
  }
};

const handleUploadError = (error: any, file: any) => {
  console.error('图片上传错误:', error);
  console.error('上传文件信息:', file);
  
  let errorMessage = '图片上传失败';
  
  if (error.response) {
    // 服务器返回错误响应
    const status = error.response.status;
    const data = error.response.data;
    
    switch (status) {
      case 400:
        errorMessage = '请求参数错误: ' + (data?.message || '请检查文件格式和大小');
        break;
      case 413:
        errorMessage = '文件太大，请选择小于5MB的图片';
        break;
      case 415:
        errorMessage = '不支持的文件类型，请上传图片文件';
        break;
      case 500:
        errorMessage = '服务器内部错误，请稍后重试';
        break;
      default:
        errorMessage = `上传失败 (${status}): ${data?.message || '未知错误'}`;
    }
  } else if (error.request) {
    // 网络错误
    errorMessage = '网络连接失败，请检查网络设置';
  } else {
    // 其他错误
    errorMessage = error.message || '上传过程中发生未知错误';
  }
  
  ElMessage.error(errorMessage);
};

const handleUploadProgress = (event: any, file: any) => {
  const percent = Math.round(event.percent);
  console.log(`上传进度: ${percent}%`);
  
  if (percent === 100) {
    ElMessage.info('文件上传完成，正在处理...');
  }
};

const beforeAvatarUpload = (file: any) => {
  console.log('开始验证上传文件:', file);
  
  // 验证文件类型
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  
  // 验证文件大小（5MB）
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  
  // 验证文件扩展名
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
  const fileName = file.name.toLowerCase();
  const hasValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext));
  
  if (!hasValidExtension) {
    ElMessage.error('只支持 JPG、PNG、GIF、BMP 格式的图片!');
    return false;
  }
  
  console.log('文件验证通过:', {
    name: file.name,
    size: (file.size / 1024 / 1024).toFixed(2) + 'MB',
    type: file.type
  });
  
  return true;
};
</script>

<style scoped>
.enterprise-manage {
  background: #f7f8fa;
  min-height: calc(100vh - 200px); /* 减去菜单和其他组件的高度 */
  padding: 0;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 0 24px;
  box-shadow: 0 2px 8px #f0f1f2;
  height: 64px;
}
.header-right {
  display: flex;
  gap: 8px;
}
.el-container {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.el-main {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-actions {
  display: flex;
  gap: 8px;
}

.search-box {
  display: flex;
  align-items: center;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.el-table {
  flex: 1;
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 16px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: right;
  z-index: 10;
  position: sticky;
  bottom: 0;
}
.batch-input-group {
  display: flex;
  align-items: center;
}

.batch-input-group .el-input {
  flex: 1;
  margin-right: 8px;
}

.batch-input-group .el-button {
  flex-shrink: 0;
}

.image-error {
  color: #f56c6c;
  font-size: 24px;
}

.no-image {
  color: #c0c4cc;
  font-size: 24px;
}

.table-row-enter-active,
.table-row-leave-active {
  transition: all 0.3s;
}

.table-row-enter-from,
.table-row-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.table-actions {
  display: flex;
  gap: 8px;
}

.el-button [class*="el-icon"] + span {
  margin-left: 4px;
}

.pagination-debug {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  display: flex;
  justify-content: space-between;
}

.loading-text {
  color: #409eff;
  font-weight: bold;
}

.badge {
  display: inline-block;
  background-color: #fff;
  color: #f56c6c;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  margin-left: 5px;
  font-weight: bold;
  min-width: 18px;
  text-align: center;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #fafafa;
}
.upload-text {
  color: #8c939d;
  font-size: 12px;
  margin-top: 8px;
}

.upload-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.upload-tip .el-icon {
  font-size: 14px;
  color: #409eff;
}
</style> 